﻿using ComClassLibrary;
using KeyboardArg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace SoftKeyBoard
{
    public partial class FormInputPassportNumber : Form
    {
        private KeyBoardArgs _keyboardArg = new KeyBoardArgs();

        public const int USER_MESSAGE_OK = 0x0405;//用户自定义消息的开始数值

        public const int USER_MESSAGE_CLEAR = 0x0406;//用户自定义消息的开始数值

        private PassportNumberKeyboard keyBoard;

        public KeyBoardArgs KeyboardArgs
        {
            get { return _keyboardArg; }
        }

        public string Number
        {
            private set;
            get;
        }

        /// <summary>
        /// 窗口隐藏事件
        /// </summary>
        public event EventHandler Hidden;
        protected void OnWndHidden()
        {
            if (Hidden != null)
            {
                Hidden(this, new EventArgs());
            }
        }

        public void SetLocation(Rectangle rect)
        {
            // 计算窗体在屏幕上的位置，使其位于屏幕中心
            int x = rect.Left + (rect.Width - Width) / 2;
            int y = rect.Top + (rect.Height - Height) / 2;

            // 设置窗体的位置
            Location = new Point(x, y);
        }

        public FormInputPassportNumber()
        {
            InitializeComponent();
        }

        public FormInputPassportNumber(KeyBoardArgs KeyBoardArgs)
                  : this()
        {
            SetInputToolArg(KeyBoardArgs);
        }

        public void SetInputToolArg(KeyBoardArgs args)
        {
            if (args == null)
            {
                return;
            }
            _keyboardArg = args;
            labelTitle.Text = _keyboardArg.Title;
            textBoxNumber.MaxLength = _keyboardArg.MaxLength;
            textBoxNumber.Text = _keyboardArg.Content;
            int CurrStation = textBoxNumber.SelectionStart;
            if (CurrStation <= 0 && !string.IsNullOrEmpty(textBoxNumber.Text))
            {
                textBoxNumber.SelectionStart = textBoxNumber.Text.Length;
            }
            textBoxNumber.Focus();
            if(keyBoard != null)
            {
                keyBoard.SetPassportType(_keyboardArg.Key);
            }
        }

        public bool Check()
        {
            if (_keyboardArg == null)
                return true;
            string content = textBoxNumber.Text.Trim();
            return Checkout.IsChinesePassPortNumber(content) 
                || Checkout.IsGAZNumber(content) 
                || Checkout.IsTWZNumber(content);
        }

        public void OnbuttonOK_Click(ref System.Windows.Forms.Message m)
        {
            if (Check())
            {
                Number = textBoxNumber.Text.Trim();
                m.Result = (IntPtr)0x00;
                string strInput = textBoxNumber.Text.Trim();
                _keyboardArg.PassageType = SendMessageType.Response;
                _keyboardArg.Content = strInput;
                _keyboardArg.Command = "OK";
                if (_keyboardArg == null || _keyboardArg.MsgReceiver == IntPtr.Zero)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
                SendMessage();
                this.DialogResult = DialogResult.OK;
                this.Hide();
                OnWndHidden();
            }
            else
            {
                m.Result = (IntPtr)0xff;
                MessageBox.Show(this,
                    "护照号码输入错误!请重新输入...",
                    "输入有误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                textBoxNumber.Focus();
            }
        }

        private void buttonCancell_Click(object sender, EventArgs e)
        {
            buttonClose_Click(null, null);
        }

        private void FormInputPassportNumber_Load(object sender, EventArgs e)
        {
            keyBoard = new PassportNumberKeyboard(this.Handle);
            keyBoard.Dock = DockStyle.Fill;
            keyBoard.TopLevel = false;
            this.panel1.Controls.Clear();
            this.panel1.Controls.Add(keyBoard);
            keyBoard.NumberKeyClick += OnNumberKeyClick;
            keyBoard.BackspaceKeyClick += ButtonBackspace_Click;
            keyBoard.Show();
            textBoxNumber.Focus();
            keyBoard.SetPassportType(_keyboardArg.Key);
        } 

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case USER_MESSAGE_OK:
                    OnbuttonOK_Click(ref m);
                    break;
                case USER_MESSAGE_CLEAR:
                    //buttonClear_Click(null, null);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        /// <summary>
        /// 键盘点击事件
        /// </summary>
        /// <param name="e"></param>
        private void OnNumberKeyClick(object sender, NumberCharClickEventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxNumber.Text))
            {
                if (textBoxNumber.Text.Trim().Length >= 9)
                {
                    MessageBox.Show("证件号码的长度不能超过9位", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            int CurrStation = textBoxNumber.SelectionStart;
            string Pre = textBoxNumber.Text.Substring(0, CurrStation);
            string Aft = textBoxNumber.Text.Substring(CurrStation);
            textBoxNumber.Text = Pre + e.Number + Aft;
            textBoxNumber.SelectionStart = CurrStation + 1;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            if (_keyboardArg == null || _keyboardArg.MsgReceiver == IntPtr.Zero)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();  
                return;
            }
            _keyboardArg.Content = "";
            _keyboardArg.Command = "Cancel";
            _keyboardArg.PassageType = SendMessageType.Response;
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            ComClassLibrary.Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();
            this.DialogResult = DialogResult.Cancel;
            this.Hide();
            OnWndHidden();
        }

        private bool SendMessage()
        {
            if (_keyboardArg.MsgReceiver == IntPtr.Zero)
            {
                MessageBox.Show("句柄错误", "句柄错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            ComClassLibrary.Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();
            return true;
        }

        private Point _mousePoint;
        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mousePoint.X = e.X;
                _mousePoint.Y = e.Y;
            }
        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int X = MousePosition.X - _mousePoint.X;
                int Y = MousePosition.Y - _mousePoint.Y;
                this.Location = new Point(X, Y);
            }
        }

        private void ButtonBackspace_Click(object sender, EventArgs e)
        {
            int CurrStation = textBoxNumber.SelectionStart;
            if (CurrStation <= 0 && !string.IsNullOrEmpty(textBoxNumber.Text))
            {
                textBoxNumber.SelectionStart = textBoxNumber.Text.Length;
            }
            CurrStation = textBoxNumber.SelectionStart;
            if (CurrStation > 0)//光标之前有文本
            {
                string Pre = textBoxNumber.Text.Substring(0, CurrStation - 1);
                string Aft = CurrStation < textBoxNumber.Text.Length ? textBoxNumber.Text.Substring(CurrStation) : "";
                textBoxNumber.Text = Pre + Aft;
                textBoxNumber.SelectionStart = CurrStation - 1;
            }
        }

        private void FormInputPassportNumber_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (keyBoard != null && keyBoard.IsHandleCreated)
            {
                keyBoard.Close();
            }
        }

    }
}
